
debugger;
accessid= document.getElementById('key_id').getAttribute('value');
accesskey= document.getElementById('key_secret').getAttribute('value');
host = document.getElementById('url').getAttribute('value');

g_dirname = ''
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000; 

var policyText = {
    "expiration": "3020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
    ["content-length-range", 0, 104857600] // 设置上传文件的大小限制
    ]
};

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
var signature = Crypto.util.bytesToBase64(bytes);

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_dirname()
{
    dir = document.getElementById("dirname").value;
    if (dir != '' && dir.indexOf('/') != dir.length - 1)
    {
        dir = dir + '/'
    }
    //alert(dir)
    g_dirname = dir
}

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {
        suffix = get_suffix(filename)
        g_object_name = g_dirname + random_string(10) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret)
{
    g_object_name = g_dirname;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

window.delete_div =function (div_id){
	div_id.remove();
}

var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'selectfiles', 
    multi_selection: true,
	container: document.getElementById('container'),
	flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
    loadIndex:null,
    filters: {
        mime_types : [ //只允许上传图片和zip文件
        { title : "video files", extensions : "MP4,TS,3GP,MPG,MPEG,MPE,DAT,VOB,ASF,AVI,FLV,F4V,WMV,ASF" }
        ],
        max_file_size : '100mb', //最大只能上传100mb的文件
        prevent_duplicates : false //不允许选取重复文件
    },

	init: {
		PostInit: function() {
			document.getElementById('ossfile').innerHTML = '';
			document.getElementById('postfiles').onclick = function() {
	            set_upload_param(uploader, '', false);
	            if(uploader.total.queued>0){
	            	loadIndex = layer.msg('上传中，请稍候...', {icon: 16,time:-1});
	            }else if(uploader.total.queued==0){
	            	layer.msg("未选择需要上传的文件",{icon: 7,time:2000});
	            }
	            return false;
			};
		},

		FilesAdded: function(up, files) {
			plupload.each(files, function(file) {
				document.getElementById('ossfile').innerHTML += '<div style="margin-left: 55px;margin-top:15px;display: inline-block" id="' + file.id + '">'
				+'<b>文件原名：' + file.name +'</b><b></b><div class="progress" style="width:130px;"><div class="progress-bar" style="width: 0%"></div></div>'
				+'<div style="padding-top: 10px"><a href="" target ="_blank" id="href-'+file.id+'">'
				+'<img src="http://bpdr.admin168.net/icon/mp4.png" style="max-width: 100px; max-height: 150px;">'
				+'</a><small class="uploads-delete-tip bg-red badge delete_small" delete_type="" style="position:absolute;" id="delete-'+file.id+'" onclick="delete_div('+file.id+')">x</small></div>'
				 +'<input type="hidden" id="inputurl_'+file.id+'" name="video_url[]" class="layui-input" value="">'
				+'</div>';
			});
		},

		BeforeUpload: function(up, file) {
            check_object_radio();
            set_upload_param(up, file.name, true);
        },

		UploadProgress: function(up, file) {
			var d = document.getElementById(file.id);
			if(d!=null){
				d.getElementsByTagName('b')[1].innerHTML = '<span>，上传进度' + file.percent + "%</span>";
	            var prog = d.getElementsByTagName('div')[0];
				var progBar = prog.getElementsByTagName('div')[0]
				progBar.style.width= file.percent+'%';
				progBar.setAttribute('aria-valuenow', file.percent+"%");
			}
		},

		FileUploaded: function(up, file, info) {
            if (info.status == 200)
            {
            	var d = document.getElementById(file.id);
                if(d!=null){
                	d.getElementsByTagName('b')[1].innerHTML = '，上传成功。';
                    document.getElementById("href-"+file.id).href=host+'/'+ get_uploaded_object_name(file.name);
                    /*document.getElementById("video-label"+file.id).src=host+'/'+ get_uploaded_object_name(file.name);*/
                    document.getElementById("inputurl_"+file.id).value=host+'/'+ get_uploaded_object_name(file.name)+"#"+file.name;
                }
                /*var body = document.getElementById(file.id); //获得ID为text的节点
                var a = document.createElement("a");  //创建一个label标签
                a.href = host+'/'+ get_uploaded_object_name(file.name); //地址
                a.target = "_blank";
                var video = document.createElement("video");
                video.style = 'width= 100%; height=100%; object-fit: fill" width="130px" height="290px';
                video.url = host+'/'+ get_uploaded_object_name(file.name); //地址
                video.autoplay="true";
                a.appendChild(video); 
                body.appendChild(a); 
                var input = document.createElement("input");
                input.type="hidden";
                input.name="video_url[]";
                input.class="layui-input";
                input.value=host+'/'+ get_uploaded_object_name(file.name); //地址
*/          }
            else if (info.status == 203)
            {
            	var d = document.getElementById(file.id);
                if(d!=null){
                	d.getElementsByTagName('b')[1].innerHTML = '上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:' + info.response;
                }
            }
            else
            {
            	var d = document.getElementById(file.id);
                if(d!=null){
                	document.getElementById(file.id).getElementsByTagName('b')[1].innerHTML = info.response;
                }
            } 
            if(up.total.queued==0){
            	layer.close(loadIndex);
            }
		},

		Error: function(up, err) {
            if (err.code == -600) {
                document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,请上传100M以内的视频"));
            }
            else if (err.code == -601) {
                document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对"));
            }
            else if (err.code == -602) {
                document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
            }
            else 
            {
                document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
            }
            if(up.total.queued==0){
            	layer.close(loadIndex);
            }
		}
	}
});

uploader.init();
